//
//  DanmakuViewController.swift
//  live
//
//  Created by melvyn on 2018/8/16.
//  Copyright © 2018 NEET. All rights reserved.
//

import UIKit
import RxDataSources

extension UITableView {
    enum RowAlignment {
        case bottom
        case top
    }
}

class DanmakuViewController: UIViewController {
    
    @IBOutlet weak var tableView: UITableView!
    
    weak var viewModel: DanmakuListViewModel?
    var dataSource: RxTableViewAnimatedDataSource<DanmakuTable>!
    var alignment: UITableView.RowAlignment = .bottom
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        
        let configuration = AnimationConfiguration.init(insertAnimation: .bottom)
        let cellMaker: (TableViewSectionedDataSource<DanmakuTable>, UITableView, IndexPath, DanmakuViewModel)
            -> UITableViewCell
            = { _, tableView, indexPath, comment -> UITableViewCell in
                let identifier = String(describing: DanmakuTableViewCell.self)
                let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) as! DanmakuTableViewCell
                cell.viewModel = comment
                return cell
        }
        
        dataSource = .init(animationConfiguration: configuration, configureCell: cellMaker)
        
        viewModel?.sections
            .drive(tableView.rx.items(dataSource: dataSource))
            .disposed(by: disposeBag)
        
        dataSource.performBatchUpdates
            .filter({ !$0.isEmpty })
            .map({ $0.last! })
            .subscribe(onNext: { [unowned self] in
                self.tableView.scrollToRow(at: $0, at: .bottom, animated: true)
                
                if self.alignment == .bottom {
                    let contentInset = self.tableView.contentInset
                    var edgeInsets = contentInset
                    edgeInsets.top = self.tableView.bounds.height
                    
                    if edgeInsets.top > contentInset.top {
                        edgeInsets.top = edgeInsets.top - self.tableView.contentSize.height
                        edgeInsets.top = edgeInsets.top < contentInset.top ? contentInset.top : edgeInsets.top
                    }
                    self.tableView.contentInset = edgeInsets
                }
            })
            .disposed(by: disposeBag)
    }
}
